package com.ljfiction.book.activitys;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.androidkun.xtablayout.XTabLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.lidroid.xutils.util.LogUtils;
import com.ljfiction.book.Baner.Bookchapters;
import com.ljfiction.book.Baner.ChapterContext;
import com.ljfiction.book.Baner.ReadAuthBookBean;
import com.ljfiction.book.Baner.ReadBaocunBean;
import com.ljfiction.book.Baner.ReadBeijingBean;
import com.ljfiction.book.Baner.ShuqianBean;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.Dialog.PhoneBangding;
import com.ljfiction.book.Dialog.SubcritTishiDialog;
import com.ljfiction.book.Dialog.ToSubcritDialog;
import com.ljfiction.book.Dialog.ToaddBookDialog;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.adapter.IndentDetailAdapter;
import com.ljfiction.book.fragment.ReadReconnt;
import com.ljfiction.book.fragment.ShuQiajn;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.Md5;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.manage.CodeManager;
import com.ljfiction.book.readview.Baocunchapter;
import com.ljfiction.book.readview.BaseReadView;
import com.ljfiction.book.readview.NoAimWidget;
import com.ljfiction.book.readview.OnReadStateChangeListener;
import com.ljfiction.book.readview.OverlappedWidget;
import com.ljfiction.book.readview.PageWidget;
import com.ljfiction.book.tools.AppUtils;
import com.ljfiction.book.tools.ImageTool;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.StringTool;
import com.ljfiction.book.tools.TimeTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.zaaach.toprightmenu.MenuItem;
import com.zaaach.toprightmenu.TopRightMenu;
import com.zhy.autolayout.utils.AutoUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.ielse.view.SwitchView;
import okhttp3.Call;
import okhttp3.Response;

public class Reading2Activity extends BaseActivity {

    @BindView(R.id.readWidget)
    FrameLayout readWidget;
    @BindView(R.id.giveread)
    RelativeLayout giveread;
    @BindView(R.id.readtop)
    LinearLayout readtop;


    @BindView(R.id.weightandnight)
    TextView weightandnight;

    @BindView(R.id.readbroom)
    LinearLayout readbroom;
    @BindView(R.id.caidanlan)
    ImageView caidanlan;

    @BindView(R.id.readtexttitle)
    TextView readtexttitle;
    @BindView(R.id.baifenbi)
    TextView baifenbi;
    @BindView(R.id.movetitle)
    LinearLayout movetitle;
    @BindView(R.id.booktitlereadcoment)
    TextView booktitlereadcoment;
    @BindView(R.id.xtablayout)
    XTabLayout xtablayout;
    @BindView(R.id.contentpager)
    ViewPager contentpager;
    @BindView(R.id.drawerlayoutread)
    DrawerLayout drawerlayoutread;
    @BindView(R.id.readbackgroud)
    LinearLayout readbackgroud;
    @BindView(R.id.nighday)
    ImageView nighday;
    @BindView(R.id.give_readxmj)
    ImageView giveReadxmj;
    private BaseReadView mPageWidget;//翻页方式
    private String bookId;//书id
    private String bookName;//书名
    private String bookwriterId;//作者Id
    private String bookwriterName;//作者昵称
    private String bookwriterImage;//作者头像
    private List<Bookchapters.DataBean.ChapterInfoBean> mContentChapterList = new ArrayList<>();//卷章节列表
    private List<Bookchapters.DataBean.ChapterInfoBean.ResultListBean> mChapterList = new ArrayList<>();//章节列表
    public static int currentChapter = 0;//开始是第一章
    private int huancunChapter2;
    private ReadBaocunBean readBaocunBean;
    public static int isgridviewselect = 0;//选中的money
    private ViewHolderGolden viewHoldertoupiao;//投票
    private ViewHolder viewHolder;//设置
    private ViewHolderreadprogressbar viewHolderreadprogressbar;//进度
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private String tabTitles[] = new String[]{"目录", "书签"};
    private Handler handler;
    /**
     * 是否开始阅读章节
     **/
    private boolean startRead = true;
    private String path;
    private BaseQuickAdapter readviewBeijingAdapter;
    private int flipwey = 1;//翻页方式,1是方正翻页，2是覆盖，3无
    private TopRightMenu mTopRightMenu;
    private ReadReconnt mulu;
    private ShuQiajn shuqian;
    private List<ShuqianBean> listshuqian = new ArrayList<>();
    private int isNight = 0;
    //是否自动订阅
    private boolean isZidong = false;
    private int seekposition;//亮度
    private BaseActivity baseActivity;
    private NoBackgLodDialog noBackgLodDialog;
    private ChapterContext chapterContext;
    private Runnable runnable, runnable1;
    private PhoneBangding phoneBangdingDialog;
    private ToSubcritDialog toSubcritDialog;
    private ReadAuthBookBean readAuthBookBean;
    private boolean isToOverpage=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reading2);
        ButterKnife.bind(this);
        baseActivity = this;
        AppUtils.init(this);
        readBaocunBean = new ReadBaocunBean();
        bookId = getIntent().getStringExtra("bookId");
        currentChapter = SettingManager.getInstance().getReadProgress(bookId)[0];
        beijingposition = SettingManager.getInstance().getBeijingcolor();
        isNight = SettingManager.getInstance().getIsNightDay();
        readBeijingBean = new ReadBeijingBean();
        seekposition = SettingManager.getInstance().getSeekposition() == 0 ? ScreenUtils.getScreenBrightness() : SettingManager.getInstance().getSeekposition();
        ScreenUtils.setScreenBrightness(seekposition, this);
        if (isNight == 1) {
            readbackgroud.setBackgroundResource(readBeijingBean.getBeijingcolort().get(readBeijingBean.getBeijingcolort().size() - 1));
        } else {
            readbackgroud.setBackgroundResource(readBeijingBean.getBeijingcolort().get(beijingposition));
        }
        flipwey = SettingManager.getInstance().getflipwey();
        initView();
        intData();


        ButterKnife.bind(this);
    }

    private boolean isshujia = false;

    //是否在书架
    private void isShujia() {
        OkHttpUtils.get(HttpManager.IP + "/bookshelf-bookshelfIsSave/" + bookId)

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject js = new JSONObject(s);
                            if (js.getInt("returnCode") == 200) {
                                isshujia = false;
                            } else if (js.getInt("returnCode") == 500) {
                                isshujia = true;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 隐藏虚拟按键，并且设置成全屏
     */
    private void hideBottomUIMenu() {
        if (Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
            decorView.setSystemUiVisibility(uiOptions);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    /**
     * 显示虚拟按键，并且设置成全屏
     */
    private void showBottomUIMenu() {
        if (Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.VISIBLE);
        } else {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    //获取是否自动订阅
    private void isZidong() {
        OkHttpUtils.post(HttpManager.IP + "/userRmemberChose")

                .params("bookid", bookId)
                .params("isSelect", "1")
                .params("type", "search")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject js = new JSONObject(s);
                            if (200 == js.getInt("returnCode")) {
                                isZidong = js.getJSONObject("data").getInt("isClose") != 0;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void toZidongView() {
        if (isZidong) {
            viewHolder.selfreadset.setOpened(true);
        } else {
            viewHolder.selfreadset.setOpened(false);
        }
    }

    //设置自动订阅或取消自动订阅
    private void toZidong(String isSelect) {
        OkHttpUtils.post(HttpManager.IP + "/userRmemberChose")

                .params("bookid", bookId)
                .params("isSelect", isSelect)
                .params("type", "update")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject js = new JSONObject(s);
                            if (200 == js.getInt("returnCode")) {
                                isZidong = js.getJSONObject("data").getInt("isClose") != 0;
                                if (popupWindowset != null) {
                                    toZidongView();
                                }
                            } else {
                                if (400 == js.getInt("returnCode")) {
                                    Intent intent = new Intent(Reading2Activity.this, LoginActivity.class);
                                    startActivity(intent);

                                }
                                showToast(js.getString("msg"));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private List<MenuItem> menuItems = new ArrayList<>();

    private void initView() {
        handler = new Handler();
        runnable = () -> {
            if (readtop.getVisibility() != View.VISIBLE) {
                giveReadxmj.setVisibility(View.GONE);
                AnimationSet aset = new AnimationSet(true);
                AlphaAnimation aa = new AlphaAnimation(1, 0);
                aa.setDuration(2000);
                aset.addAnimation(aa);
                giveReadxmj.startAnimation(aset);
            }
        };
        handler.postDelayed(runnable, 5000);
        if (isNight == 0) {
            weightandnight.setText("夜间");
            nighday.setImageResource(R.drawable.nightread);
        } else {
            weightandnight.setText("白天");
            nighday.setImageResource(R.drawable.sunread);
        }
        mTopRightMenu = new TopRightMenu(Reading2Activity.this);
        menuItems.add(new MenuItem("书籍详情"));
        menuItems.add(new MenuItem("查看书评"));
        menuItems.add(new MenuItem("加入书架"));
        menuItems.add(new MenuItem("添加书签"));
        menuItems.add(new MenuItem("举报本章"));
        menuItems.add(new MenuItem("分享本书"));
        mTopRightMenu
                .setHeight(ScreenUtils.getNum(Reading2Activity.this, 300))     //默认高度480
                .setWidth(ScreenUtils.getNum(Reading2Activity.this, 120))      //默认宽度wrap_content
                .showIcon(false)     //显示菜单图标，默认为true
                .dimBackground(true)//背景变暗，默认为true
                .needAnimationStyle(true)   //显示动画，默认为true
                .setAnimationStyle(R.style.TRM_ANIM_STYLE)  //默认为R.style.TRM_ANIM_STYLE
                .addMenuList(menuItems)
                .setOnMenuItemClickListener(position -> {
                    switch (position) {
                        case 0:
                          /*  mPageWidget.recycleBitmap();
                            mPageWidget = null;
                            System.gc();
                            System.runFinalization();
                            System.gc();*/
                            Intent intentread = new Intent(Reading2Activity.this, BookDetailsActivity.class);
                            intentread.putExtra("bookId", bookId);
                            startActivityForResult(intentread, 7);
                            break;
                        case 1:
                            Intent intentshuping = new Intent(this, AuthShuPingActivity.class);
                            intentshuping.putExtra("bookId", bookId);
                            intentshuping.putExtra("bookName", bookName);
                            startActivity(intentshuping);
                            break;
                        case 2:
                            if (!UserManageBean.isLogin(Reading2Activity.this)) {
                                return;
                            } else {
                                toAddBook();
                            }
                            break;
                        case 3:
                            listshuqian = SettingManager.getInstance().getShuqian(bookId);
                            listshuqian.add(new ShuqianBean(mChapterList.get(currentChapter).getChapterId(), mPageWidget.getReadPos(), mChapterList.get(currentChapter).getChapterTitle(), String.valueOf(((float) (currentChapter + 1) / mChapterList.size()) * 100) + "%", mPageWidget.getHeadLine(), TimeTool.getCurrenttime()));
                            SettingManager.getInstance().setShuqian(bookId, listshuqian);
                            shuqian.gengxin();
                            showToast("添加成功！");
                            break;
                        case 4:
                            showToast("举报成功！");
                            break;
                        case 5:
                            Intent intent = new Intent(Reading2Activity.this, InviteActivity.class);
                            intent.putExtra("bookName", bookName);
                            intent.putExtra("bookId", bookId);
                            intent.putExtra("bookImage", readAuthBookBean.getData().getBookInfo().getBookImage());
                            startActivityForResult(intent, CodeManager.invite_friends);
                            break;
                    }
                });
    }

    //加入书架
    private void toAddBook() {
        OkHttpUtils.post(HttpManager.IP + "/bookshelf-adduserbookshelf")

                .params("userName", UserManageBean.userBean.getPseudonym())
                .params("bookId", bookId)
                .params("bookName", bookName)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject js = new JSONObject(s);
                            if (js.getInt("returnCode") == 200) {
                                isshujia = !isshujia;
                            } else if (js.getInt("returnCode") == 400) {
                                Intent intent = new Intent(Reading2Activity.this, LoginActivity.class);
                                startActivity(intent);
                            }
                            showToast(js.getString("msg"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    private void intData() {
        //获取章节列表
        OkHttpUtils.get(HttpManager.IP + "/books-volumeChapterList/" + bookId)

                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (noBackgLodDialog==null){
                            noBackgLodDialog=new NoBackgLodDialog(Reading2Activity.this,false);
                        }
                        noBackgLodDialog.show();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (noBackgLodDialog.isShowing()){
                            noBackgLodDialog.dismis();
                        }
                        Gson gson = new Gson();
                        try {
                            Bookchapters bookchapters = gson.fromJson(s, Bookchapters.class);
                            if (200 == bookchapters.getReturnCode()) {
                                for (Bookchapters.DataBean.ChapterInfoBean i :
                                        bookchapters.getData().getChapterInfo()) {
                                    mChapterList.addAll(i.getResultList());
                                }
                                mContentChapterList = bookchapters.getData().getChapterInfo();
                                if (mContentChapterList.size() == 0) {
                                    showToast("这本书还没有内容");
                                    goBack();
                                    return;
                                } else if (mChapterList.size() == 0) {
                                    showToast("这本书还没有内容");
                                    goBack();
                                    return;
                                }
                                bookName = mChapterList.get(0).getBookTitle();
                                booktitlereadcoment.setText(bookName);
                                bookwriterId = String.valueOf(mChapterList.get(0).getBookWriterId());
                                togiveAuthorxinxi();


                                //从历史纪录过来
                                if (getIntent().getIntExtra("type", 0) == 1) {
                                    int chapterId = getIntent().getIntExtra("chapterId", mChapterList.get(0).getChapterId());
                                    for (int i = 0; i < mChapterList.size(); i++) {
                                        if (chapterId == mChapterList.get(i).getChapterId()) {
                                            SettingManager.getInstance().saveReadProgress(bookId, i, 0, 0, 1, 0);
                                            break;
                                        }
                                    }
                                }
                                if (SettingManager.getInstance().getReadProgress(bookId)[0] > mChapterList.size() - 1) {
                                    SettingManager.getInstance().saveReadProgress(bookId, 0, 0, 0, 1, 0);
                                }
                                intdrawbalview();
                                initPagerWidget();
                            } else {
                                showToast(bookchapters.getMsg());
                                goBack();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            goBack();
                        }
                    }
                });

    }

    //获取作者的信息
    private void togiveAuthorxinxi() {
        OkHttpUtils.post(HttpManager.IP + "/getAuthorInfoBySimplify")
                .params("bookId", bookId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {

                        try {
                            Gson gson = new Gson();
                            readAuthBookBean = gson.fromJson(s, ReadAuthBookBean.class);
                            if (200 == (readAuthBookBean.getReturnCode())) {
                                bookwriterImage = readAuthBookBean.getData().getAuthorInfo().getAuthorHeadImg();
                                bookwriterName = readAuthBookBean.getData().getAuthorInfo().getAuthorName();
                                /*
                                 * Glide 加载图片保存到本地
                                 *
                                 * imgUrl 图片地址
                                 * imgName 图片名称
                                 */
                                Glide.with(Reading2Activity.this).load(bookwriterImage).asBitmap().into(new SimpleTarget<Bitmap>() {
                                    @Override
                                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                        mPageWidget.setauthorImage(ImageTool.toRoundBitmap(resource));
                                    }
                                });
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

    }

    private IntentFilter intentFilter = new IntentFilter();

    private void initPagerWidget() {
        switch (flipwey) {
            case 1:
                mPageWidget = new PageWidget(this, bookId, mChapterList, readlistener, readBaocunBean);
                break;
            case 2:
                mPageWidget = new OverlappedWidget(this, bookId, mChapterList, readlistener, readBaocunBean);
                break;
            case 3:
                mPageWidget = new NoAimWidget(this, bookId, mChapterList, readlistener, readBaocunBean);
                break;
        }
        mPageWidget.init();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        if (receiver == null) {
            receiver = new Receiver();
            registerReceiver(receiver, intentFilter);
        }

        readWidget.removeAllViews();
        readWidget.addView(mPageWidget);
        hideBottomUIMenu();
    }

    @SuppressLint({"RtlHardcoded", "SetTextI18n"})
    @OnClick({R.id.rewardreadtext, R.id.goldenreadtext, R.id.caidanlan, R.id.catalogue, R.id.readset, R.id.schedule, R.id.readneight, R.id.back_read, R.id.give_readxmj})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rewardreadtext:
                if (readtop.getVisibility() == View.VISIBLE) {
                    hideorshowbottom();
                }
                toshowsubscrib();
                break;

            case R.id.goldenreadtext:
                if (readtop.getVisibility() == View.VISIBLE) {
                    hideorshowbottom();
                }
                if (popupWindowgive != null && !popupWindowgive.isShowing()) {
                    popupWindowgive.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                } else {
                    showPopuWindow(view, 3);
                }
                break;
            case R.id.caidanlan:
                mTopRightMenu.showAsDropDown(caidanlan, -ScreenUtils.getNum(Reading2Activity.this, 80), ScreenUtils.getNum(Reading2Activity.this, 15));

                break;
            case R.id.catalogue:
                if (readtop.getVisibility() == View.VISIBLE) {
                    hideorshowbottom();
                }
                mulu.toscroll(mChapterList.get(currentChapter).getVolumeId(), mChapterList.get(currentChapter).getChapterId());
                drawerlayoutread.openDrawer(Gravity.LEFT);
                break;
            case R.id.readset:
                if (readtop.getVisibility() == View.VISIBLE) {
                    hideorshowbottom();
                }
                if (popupWindowset != null && !popupWindowset.isShowing()) {
                    popupWindowset.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                } else {
                    showPopuWindow(view, 1);
                }
                break;
            case R.id.schedule:
                if (readtop.getVisibility() == View.VISIBLE) {
                    hideorshowbottom();
                }
                if (popuWindoeprogressbar != null && !popuWindoeprogressbar.isShowing()) {
                    popuWindoeprogressbar.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                    viewHolderreadprogressbar.readseekbar.setProgress((currentChapter + 1) * 100 / mChapterList.size());
                } else {
                    showPopuWindow(view, 4);
                }
                if (runnable1 == null) {
                    runnable1 = () -> {
                        movetitle.setVisibility(View.VISIBLE);
                        movetitle.setTranslationX(ScreenUtils.getNum(Reading2Activity.this, (currentChapter + 1) * 300 / mChapterList.size()));
                        readtexttitle.setText(mChapterList.get(currentChapter).getChapterTitle());
                        baifenbi.setText(String.valueOf((float) ((currentChapter + 1) * 100 / mChapterList.size())) + "%");
                    };
                }
                handler.postDelayed(runnable1, 200);
                break;

            case R.id.readneight:
                if (isNight == 1) {
                    mPageWidget.setBeijing(beijingposition);
                    readbackgroud.setBackgroundResource(readBeijingBean.getBeijingcolort().get(beijingposition));
                    nighday.setImageResource(R.drawable.nightread);
                    weightandnight.setText("夜间");
                    isNight = 0;
                } else {
                    mPageWidget.setBeijing(readBeijingBean.getBeijingcolort().size() - 1);
                    readbackgroud.setBackgroundResource(readBeijingBean.getBeijingcolort().get(readBeijingBean.getBeijingcolort().size() - 1));
                    nighday.setImageResource(R.drawable.sunread);
                    weightandnight.setText("白天");
                    isNight = 1;
                }

                break;

            case R.id.back_read:
                if (UserManageBean.isLogin() && !isshujia) {
                    isToAddShujia();
                } else {
                    goBack();
                }
                break;
            case R.id.give_readxmj:
                if (!UserManageBean.isLogin(Reading2Activity.this)) {
                    return;
                }
                if (UserManageBean.userBean.getUserRecommendTicket() < 1) {
                    if (readtop.getVisibility() == View.VISIBLE) {
                        hideorshowbottom();
                    }
                    toshowsubscrib();
                } else {
                    if (UserManageBean.userBean.getUserPhone().equals("0")) {
                        if (phoneBangdingDialog == null) {
                            phoneBangdingDialog = new PhoneBangding(Reading2Activity.this);
                            phoneBangdingDialog.setListener(new PhoneBangding.Listener() {
                                @Override
                                public void giveyanzhengnoLogin() {
                                    Intent intent = new Intent(Reading2Activity.this, LoginActivity.class);
                                    startActivity(intent);

                                }

                                @Override
                                public void setok() {
                                    UserManageBean.backgroundRiches(Reading2Activity.this);
                                }

                                @Override
                                public void clickquhao() {
                                    Intent intent = new Intent(Reading2Activity.this, SelectquhaoActivity.class);
                                    startActivityForResult(intent, CodeManager.Binding_read);
                                }
                            });
                        }
                        phoneBangdingDialog.show();

                        return;
                    }
                    toTouweixmj();
                }
                break;
        }
    }

    //弹出打上的页面
    private void toshowsubscrib() {
        if (toSubcritDialog == null) {
            toSubcritDialog = new ToSubcritDialog(Reading2Activity.this, bookId, bookName, bookwriterId);
            toSubcritDialog.setListener(new ToSubcritDialog.Listener() {
                @Override
                public void subclickok() {
                }

                @Override
                public void subnologin() {
                    Intent intent = new Intent(Reading2Activity.this, LoginActivity.class);
                    startActivity(intent);
                }
            });
        } else {
            toSubcritDialog.show();
        }
    }

    //弹出是否加入书架
    private void isToAddShujia() {
        if (toaddBookDialog == null) {
            toaddBookDialog = new ToaddBookDialog(baseActivity, "这本书还没有加入书架，现在帮你加入书架？", "收藏书籍");
            toaddBookDialog.setListener(new ToaddBookDialog.Listener() {
                @Override
                public void okClick() {
                    OkHttpUtils.post(HttpManager.IP + "/bookshelf-adduserbookshelf")

                            .params("userName", UserManageBean.userBean.getPseudonym())
                            .params("bookId", bookId)
                            .params("bookName", bookName)
                            .execute(new StringCallback() {
                                @Override
                                public void onSuccess(String s, Call call, Response response) {
                                    try {
                                        JSONObject js = new JSONObject(s);
                                        if (js.getInt("returnCode") == 200) {
                                            goBack();
                                        } else if (js.getInt("returnCode") == 400) {
                                            Intent intent = new Intent(Reading2Activity.this, LoginActivity.class);
                                            startActivity(intent);
                                        }
                                        showToast(js.getString("msg"));
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                }

                @Override
                public void closeClick() {
                    goBack();
                }
            });

        } else {
            toaddBookDialog.show();
        }
    }

    public OnReadStateChangeListener readlistener = new OnReadStateChangeListener() {
        @Override
        public synchronized void onChapterChanged(int chapter) {
            currentChapter = chapter;
            getChapterContext(chapter);
            if (chapter - 1 >= 0) {
                getChapterContext(chapter - 1);
            }
            if (chapter + 1 < mChapterList.size()) {
                getChapterContext(chapter + 1);
            }
        }

        @Override
        public void onPageChanged(int chapter, int page) {
            LogUtils.i("onPageChanged:" + chapter + "-" + page);
        }

        @Override
        public void onLoadChapterFailure(final int chapter) {
            LogUtils.i("onLoadChapterFailure:" + chapter);
            huancunChapter2 = chapter;
            OkHttpUtils.post(HttpManager.IP + "/book-read")

                    .params("chapterId", mChapterList.get(huancunChapter2).getChapterId() + "")
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            goBack();
                        }

                        @Override
                        public void onBefore(BaseRequest request) {
                            super.onBefore(request);
                            if (noBackgLodDialog == null) {
                                noBackgLodDialog = new NoBackgLodDialog(Reading2Activity.this, true);
                            }
                            noBackgLodDialog.show();
                        }

                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            if (noBackgLodDialog.isShowing()) {
                                noBackgLodDialog.dismis();
                            }
                            if (SettingManager.getInstance().getFirst() == 0) {
                                readtop.setVisibility(View.VISIBLE);
                                readbroom.setVisibility(View.VISIBLE);
                                showBottomUIMenu();
                                giveReadxmj.setVisibility(View.VISIBLE);
                                new SubcritTishiDialog(Reading2Activity.this);
                                SettingManager.getInstance().saveFirst();
                            }
                            try {
                                Gson gson = new Gson();
                                chapterContext = gson.fromJson(s, ChapterContext.class);
                                if (200 == chapterContext.getReturnCode()) {
                                    path = StringTool.getChaptertext(chapterContext.getData().getChapterInfo().getChapterContent());
                                    if (readBaocunBean.getContextMap().get(huancunChapter2) == null) {
                                        readBaocunBean.getContextMap().put(huancunChapter2, new Baocunchapter());
                                    }
                                    readBaocunBean.getContextMap().get(huancunChapter2).setChapterid(chapterContext.getData().getChapterInfo().getId());
                                    readBaocunBean.getContextMap().get(huancunChapter2).setVolemuid(chapterContext.getData().getChapterInfo().getVolumeId());
                                    readBaocunBean.getContextMap().get(huancunChapter2).setContext(path.getBytes());
                                    readBaocunBean.getContextMap().get(huancunChapter2).setCountnum(chapterContext.getData().getCountInfos());
                                    readBaocunBean.getContextMap().get(huancunChapter2).setVip(false);
                                    readBaocunBean.getContextMap().get(huancunChapter2).setVipnum(chapterContext.getData().getChapterInfo().getPrice());
                                    toUUID(chapterContext.getData().getChapterInfo().getChapterContent(), huancunChapter2);
                                } else if (500 == chapterContext.getReturnCode() || 400 == chapterContext.getReturnCode()) {
                                    path = StringTool.getChaptertext(chapterContext.getData().getChapterInfo().getChapterContent());
                                    if (readBaocunBean.getContextMap().get(huancunChapter2) == null) {
                                        readBaocunBean.getContextMap().put(huancunChapter2, new Baocunchapter());
                                    }
                                    readBaocunBean.getContextMap().get(huancunChapter2).setChapterid(chapterContext.getData().getChapterInfo().getId());
                                    readBaocunBean.getContextMap().get(huancunChapter2).setVolemuid(chapterContext.getData().getChapterInfo().getVolumeId());
                                    readBaocunBean.getContextMap().get(huancunChapter2).setContext(path.getBytes());
                                    readBaocunBean.getContextMap().get(huancunChapter2).setCountnum(chapterContext.getData().getCountInfos());
                                    readBaocunBean.getContextMap().get(huancunChapter2).setVip(true);
                                    if (isZidong) {
                                        if (startRead) {
                                            tobuyThis(huancunChapter2, 1, isZidong);
                                        } else {
                                            tobuyThis(huancunChapter2, 0, isZidong);
                                        }
                                        startRead = false;
                                    } else {
                                        toUUID(chapterContext.getData().getChapterInfo().getChapterContent(), huancunChapter2);
                                    }
                                } else {
                                    showToast(chapterContext.getMsg());
                                    goBack();
                                    return;
                                }
                                if (SettingManager.getInstance().getReadProgress(bookId)[0] == huancunChapter2 && !readBaocunBean.getContextMap().get(huancunChapter2).isVip()) {
                                    mPageWidget.setPosition(SettingManager.getInstance().getReadProgress(bookId));
                                } else {
                                    mPageWidget.setPosition(new int[]{huancunChapter2, 0, 0, 1, 0});
                                }
                                readlistener.onChapterChanged(huancunChapter2);
                            } catch (Exception e) {
                                e.printStackTrace();
                                showToast("数据异常");
                                goBack();
                            }
                        }
                    });


            /*if (CacheManager.getInstance().getChapterFile(bookId, chapter) == null)
                mPresenter.getChapterRead(mChapterList.get(chapter - 1).link, chapter);*/
        }

        @Override
        public void onCenterClick() {
            LogUtils.i("onCenterClick");
            hideorshowbottom();
        }

        @Override
        public boolean isBarhit() {
            return readbroom.getVisibility() == View.VISIBLE;
        }

        @Override
        public void onFlip() {

        }

        @SuppressLint("RtlHardcoded")
        @Override
        public void toChapter(int[] pos) {
            mPageWidget.setPosition(pos);
            drawerlayoutread.closeDrawer(Gravity.LEFT);
        }

        @Override
        public void dianseclect(String uuid, String chaptertext) {
            Intent intentdian = new Intent(Reading2Activity.this, ReadDuanpingActivity.class);
            intentdian.putExtra("uuid", uuid);
            intentdian.putExtra("chapteTitle", mChapterList.get(currentChapter).getChapterTitle());
            intentdian.putExtra("chaptertext", chaptertext);
            intentdian.putExtra("chapterId", mChapterList.get(currentChapter).getId());
            intentdian.putExtra("bookId", bookId);
            intentdian.putExtra("bookName", mChapterList.get(currentChapter).getBookTitle());
            startActivityForResult(intentdian, CodeManager.Segment_review_read);
        }

        @Override
        public void tobuy(boolean isSelectzidong) {
            if (UserManageBean.isLogin(Reading2Activity.this)) {
                tobuyThis(currentChapter, 1, isSelectzidong);
                if (isSelectzidong) {
                    isZidong = true;
                    toZidong("1");
                }
            }
        }

        @Override
        public void toInvite() {
            if (readAuthBookBean != null) {
                Intent intent = new Intent(Reading2Activity.this, InviteActivity.class);
                intent.putExtra("bookId", bookId);
                intent.putExtra("bookName", bookName);
                intent.putExtra("bookImage", readAuthBookBean.getData().getBookInfo().getBookImage());
                startActivity(intent);
            } else {
                showToast("不好意思出错了！");
            }

        }


        @Override
        public void isOverPage() {
            if (bookwriterImage==null||isToOverpage){
                return;
            }
            isToOverpage=true;
            Intent intent = new Intent(Reading2Activity.this, ReadOverpageActivity.class);
            intent.putExtra("bookId", bookId);
            intent.putExtra("bookName", bookName);
            intent.putExtra("bookwriterId", bookwriterId);
            intent.putExtra("bookwriterImage", bookwriterImage);
            intent.putExtra("bookwriterName", bookwriterName);
            intent.putExtra("bookstatus",readAuthBookBean.getData().getBookInfo().getBookStatus());
            intent.putExtra("bookClassificationid", readAuthBookBean.getData().getBookInfo().getBookClassificationId());
            startActivityForResult(intent,CodeManager.istoOverpage);
        }
    };

    //隐藏top,bottom,image;
    private void hideorshowbottom() {
        if (readtop.getVisibility() == View.VISIBLE) {
            readtop.setVisibility(View.GONE);
            readtop.setAnimation(AnimationUtils.loadAnimation(Reading2Activity.this, R.anim.read_top_out));
            giveReadxmj.setVisibility(View.GONE);
            toShowImage(false);
            readbroom.setVisibility(View.GONE);
            readbroom.setAnimation(AnimationUtils.loadAnimation(Reading2Activity.this, R.anim.read_bottom_out));
            hideBottomUIMenu();
        } else {
            readtop.setVisibility(View.VISIBLE);
            readtop.setAnimation(AnimationUtils.loadAnimation(Reading2Activity.this, R.anim.read_top_in));
            giveReadxmj.setVisibility(View.VISIBLE);
            toShowImage(true);
            readbroom.setVisibility(View.VISIBLE);
            readbroom.setAnimation(AnimationUtils.loadAnimation(Reading2Activity.this, R.anim.read_bottom_in));
            showBottomUIMenu();
        }


    }

    //订阅一个章节,type是点击购买还是自动购买,0是自动购买，1是点击购买,iszidong以后是否自动购买
    private void tobuyThis(final int mchapter, final int typeZiong, final boolean iszidong) {
        Log.v("draw9", mchapter + "");
        OkHttpUtils.post(HttpManager.IP + "/book-subscription")

                .params("userName", UserManageBean.userBean.getPseudonym())
                .params("bookId", bookId)
                .params("bookName", mChapterList.get(mchapter).getBookTitle())
                .params("bookChapterId", String.valueOf(mChapterList.get(mchapter).getChapterId()))
                .params("bookChapterName", mChapterList.get(mchapter).getChapterTitle())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject js = new JSONObject(s);
                            if (js.getInt("returnCode") == 200) {
                                UserManageBean.backgroundRiches(Reading2Activity.this);
                                if (iszidong && typeZiong == 1) {
                                    if (mchapter - 1 >= 0) {
                                        readBaocunBean.getContextMap().remove(mchapter - 1);
                                    }
                                    if (mchapter + 1 <= mChapterList.size()) {
                                        readBaocunBean.getContextMap().remove(mchapter + 1);
                                    }
                                    //在缓存中删除本章重新申请
                                    readBaocunBean.getContextMap().remove(mchapter);
                                    readlistener.onChapterChanged(mchapter);
                                } else {
                                    //在缓存中删除本章重新申请
                                    readBaocunBean.getContextMap().remove(mchapter);
                                    getChapterContext(mchapter);
                                }
                                if (typeZiong == 1) {
                                    //如果是手动点击订阅，清楚缓存重新请求
                                    readBaocunBean.getContextMap().clear();
                                    mPageWidget.setPosition(new int[]{mchapter, 0, 0, 1, 0});
                                }
                            } else if (js.getInt("returnCode") == 300 && typeZiong == 1) {
                                showToast(js.getString("msg"));
                                Intent intent = new Intent(Reading2Activity.this, PursActivity.class);
                                startActivityForResult(intent, CodeManager.purs_read);

                            } else if (js.getInt("returnCode") != 300 || typeZiong != 0) {
                                if (js.getInt("returnCode") == 400) {
                                    Intent intent = new Intent(baseActivity, LoginActivity.class);
                                    startActivity(intent);
                                }
                                showToast(js.getString("msg"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });

    }

    /**
     * 获取当前章节。章节文件存在则直接阅读，不存在则请求
     */
   /* public void readCurrentChapter() {
        if (CacheManager.getInstance().getChapterFile(bookId, currentChapter) != null) {
            showChapterRead(null, currentChapter);
        } else {
            mPresenter.getChapterRead(mChapterList.get(currentChapter - 1).link, currentChapter);
        }
    }*/
    private void getChapterContext(final int thischapter) {
        if (readBaocunBean.getContextMap().get(thischapter) != null) {
            return;
        }
        OkHttpUtils.post(HttpManager.IP + "/book-read")

                .params("chapterId", mChapterList.get(thischapter).getChapterId() + "")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        try {
                            chapterContext = gson.fromJson(s, ChapterContext.class);
                            if (200 == chapterContext.getReturnCode()) {
                                path = StringTool.getChaptertext(chapterContext.getData().getChapterInfo().getChapterContent());
                                if (readBaocunBean.getContextMap().get(thischapter) == null) {
                                    readBaocunBean.getContextMap().put(thischapter, new Baocunchapter());
                                }
                                readBaocunBean.getContextMap().get(thischapter).setChapterid(chapterContext.getData().getChapterInfo().getId());
                                readBaocunBean.getContextMap().get(thischapter).setVolemuid(chapterContext.getData().getChapterInfo().getVolumeId());
                                readBaocunBean.getContextMap().get(thischapter).setContext(path.getBytes());
                                readBaocunBean.getContextMap().get(thischapter).setCountnum(chapterContext.getData().getCountInfos());
                                readBaocunBean.getContextMap().get(thischapter).setVip(false);
                                toUUID(chapterContext.getData().getChapterInfo().getChapterContent(), thischapter);
                            } else if (400 == chapterContext.getReturnCode() || 500 == chapterContext.getReturnCode()) {
                                path = StringTool.getChaptertext(chapterContext.getData().getChapterInfo().getChapterContent());
                                if (readBaocunBean.getContextMap().get(thischapter) == null) {
                                    readBaocunBean.getContextMap().put(thischapter, new Baocunchapter());
                                }
                                readBaocunBean.getContextMap().get(thischapter).setChapterid(chapterContext.getData().getChapterInfo().getId());
                                readBaocunBean.getContextMap().get(thischapter).setVolemuid(chapterContext.getData().getChapterInfo().getVolumeId());
                                readBaocunBean.getContextMap().get(thischapter).setContext(path.getBytes());
                                readBaocunBean.getContextMap().get(thischapter).setCountnum(chapterContext.getData().getCountInfos());
                                readBaocunBean.getContextMap().get(thischapter).setVip(true);
                                if (!isZidong) {
                                    toUUID(chapterContext.getData().getChapterInfo().getChapterContent(), thischapter);
                                } else {
                                    tobuyThis(thischapter, 0, true);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    private void intdrawbalview() {
        mulu = ReadReconnt.newInstance(mContentChapterList).setReadListener(readlistener);
        shuqian = ShuQiajn.newInstance(bookId).setReadListener(readlistener);
        fragments.add(mulu);
        fragments.add(shuqian);
        IndentDetailAdapter adapter = new IndentDetailAdapter(getSupportFragmentManager(), tabTitles, fragments);
        contentpager.setAdapter(adapter);
        contentpager.setOverScrollMode(View.OVER_SCROLL_NEVER);
        xtablayout.setupWithViewPager(contentpager);
        drawerlayoutread.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (UserManageBean.isLogin() && !isshujia) {
                    isToAddShujia();
                } else {
                    goBack();
                }
                break;
            case KeyEvent.KEYCODE_MENU:
                //toggleReadBar();
                return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if (SettingManager.getInstance().isVolumeFlipEnable()) {
                    return true;
                }
                break;
            case KeyEvent.KEYCODE_VOLUME_UP:
                if (SettingManager.getInstance().isVolumeFlipEnable()) {
                    return true;
                }
                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            if (SettingManager.getInstance().isVolumeFlipEnable()) {
                mPageWidget.nextPage();
                return true;// 防止翻页有声音
            }
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            if (SettingManager.getInstance().isVolumeFlipEnable()) {
                mPageWidget.prePage();
                return true;
            }
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mPageWidget != null) {
            try {
                int[] pos = mPageWidget.getReadPos();
                if (readBaocunBean.getContextMap().get(pos[0]).isVip()) {
                    SettingManager.getInstance().saveReadProgress(bookId, pos[0], 0, 0, 1, 0);
                } else {
                    SettingManager.getInstance().saveReadProgress(bookId, pos[0], pos[1], pos[2], pos[3], pos[4]);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
            SettingManager.getInstance().saveFontSize(mPageWidget.getFontSize());
            SettingManager.getInstance().saveFontSize(bookId, mPageWidget.getFontSize());
            SettingManager.getInstance().saveIsNightDay(isNight);
            SettingManager.getInstance().saveBeijingcolor(beijingposition);
            SettingManager.getInstance().saveflipwey(flipwey);
            SettingManager.getInstance().saveBookChapterid(bookId, mChapterList.get(currentChapter).getChapterId());
            SettingManager.getInstance().saveBookVolumid(bookId, mChapterList.get(currentChapter).getVolumeId());
            SettingManager.getInstance().saveSeekPosition(seekposition);
        }

    }


    private ToaddBookDialog toaddBookDialog;

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
        if (readlistener != null) {
            readlistener = null;
        }
        if (mPageWidget != null) {
            mPageWidget.recycleBitmap();
            mPageWidget = null;
        }
        handler.removeCallbacks(runnable);
        handler.removeCallbacks(runnable1);
        readBaocunBean.getContextMap().clear();
        if (mChapterList.size() > 0) {
            if (UserManageBean.isLogin()) {
                OkHttpUtils.post(HttpManager.IP + "/person-addBookReadRecord")

                        .params("userName", UserManageBean.userBean.getPseudonym())
                        .params("bookId", bookId)
                        .params("bookName", bookName)
                        .params("chapterId", String.valueOf(mChapterList.get(currentChapter).getId()))
                        .params("chapterName", mChapterList.get(currentChapter).getChapterTitle())
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                SettingManager.finishInstance();
                            }
                        });
            }
        } else {
            SettingManager.finishInstance();
        }
        readBaocunBean = null;
        mChapterList = null;

        System.gc();
        System.runFinalization();
        System.gc();

    }


    private synchronized void toUUID(String text, Integer chapter) {
        Pattern pattern = Pattern.compile("<LG>[a-zA-Z\\d-]{36}</LG>");
        Matcher m = pattern.matcher(text);
        while (m.find()) {
            readBaocunBean.getContextMap().get(chapter).getDianlist().add(m.group().replaceAll("<LG>", "").replaceAll("</LG>", ""));
        }
    }

    private PopupWindow popupWindowset, popupWindowgive, popuWindoeprogressbar;
    private int beijingposition = 0;//背景所属坐标
    private ReadBeijingBean readBeijingBean;

    @SuppressLint({"InflateParams", "SetTextI18n"})
    private void showPopuWindow(View view, int i) {
        View contentView;

        switch (i) {
            case 1://设置
                contentView = LayoutInflater.from(this).inflate(R.layout.readset, null);
                popupWindowset = new PopupWindow(contentView);
                viewHolder = new ViewHolder(contentView);
                //toflipwayselect();//设置翻页方式的选择状态

                toZidongView();//设置是否自动订阅的选择状态
                viewHolder.readsetbeijinglist.setLayoutManager(new GridLayoutManager(Reading2Activity.this, 6));
                viewHolder.readsetbeijinglist.setAdapter(readviewBeijingAdapter = new BaseQuickAdapter<Integer, BaseViewHolder>(R.layout.readbeijing, readBeijingBean.getBeijinglist()) {
                    @Override
                    protected void convert(BaseViewHolder helper, Integer item) {
                        AutoUtils.autoSize(helper.itemView);
                        if (helper.getLayoutPosition() == beijingposition) {
                            ((ImageView) helper.getView(R.id.bejingmap)).setImageResource(readBeijingBean.getBeijingselectlist().get(beijingposition));
                        } else {
                            ((ImageView) helper.getView(R.id.bejingmap)).setImageResource(readBeijingBean.getBeijinglist().get(helper.getLayoutPosition()));
                        }
                    }
                });
                viewHolder.zitinumread.setText(String.valueOf(ScreenUtils.getpxNum(mPageWidget.getFontSize())));
                readviewBeijingAdapter.setOnItemClickListener((adapter, view1, position) -> {
                    mPageWidget.setBeijing(position);
                    beijingposition = position;
                    readbackgroud.setBackgroundResource(readBeijingBean.getBeijingcolort().get(beijingposition));
                    readviewBeijingAdapter.notifyDataSetChanged();
                });
                viewHolder.sunseekbarread.setProgress(seekposition);
                viewHolder.sunseekbarread.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        ScreenUtils.setScreenBrightness(progress, Reading2Activity.this);
                        seekposition = progress;
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {

                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {

                    }
                });
                viewHolderClick(viewHolder.addzitiread);
                viewHolderClick(viewHolder.zitisubtractread);
                viewHolderClick(viewHolder.zitisystem);
                viewHolderClick(viewHolder.selfreadset);
                viewHolderClick(viewHolder.runseekbarxitong);
                //使其聚集
                popupWindowset.setFocusable(true);
                // 设置允许在外点击消失
                popupWindowset.setOutsideTouchable(true);
                //这个是为了点击“返回Back”也能使其消失，并且并不会影响背景
                popupWindowset.setBackgroundDrawable(new BitmapDrawable(getResources()));
                // 设置SelectPicPopupWindow弹出窗体的宽
                popupWindowset.setWidth(ScreenUtils.getScreenWidth());
                popupWindowset.setHeight(ScreenUtils.getScreenHeight() * 25 / 92);
                // 设置SelectPicPopupWindow弹出窗体动画效果
                popupWindowset.setAnimationStyle(R.style.AnimBottom);
                //popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.back_search_img));
                popupWindowset.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                break;


            case 3://投票
                contentView = LayoutInflater.from(this).inflate(R.layout.read_givegolden, null);
                viewHoldertoupiao = new ViewHolderGolden(contentView);
                viewHoldertoupiao.jinjiaobalance.setText("金椒余额: " + String.valueOf(UserManageBean.userBean.getUserGoldenTicket()));
                viewHoldertoupiao.readSubtract.setOnClickListener(v -> {
                    if (Integer.valueOf(viewHoldertoupiao.readJinjiaonum.getText().toString()) <= 0) {
                        showToast("主人，不能再少啦！");
                    } else {
                        viewHoldertoupiao.readJinjiaonum.setText(String.valueOf(Integer.valueOf(viewHoldertoupiao.readJinjiaonum.getText().toString()) - 1));
                    }
                });


                viewHoldertoupiao.readAdd.setOnClickListener(v -> {
                    if (Integer.valueOf(viewHoldertoupiao.readJinjiaonum.getText().toString()) >= 10) {
                        showToast("主人，金椒很珍贵，省着点用吧！");
                    } else {
                        viewHoldertoupiao.readJinjiaonum.setText(String.valueOf(Integer.valueOf(viewHoldertoupiao.readJinjiaonum.getText().toString()) + 1));
                    }
                });

                viewHoldertoupiao.readAll.setOnClickListener(v -> {
                    if (!(UserManageBean.userBean.getUserGoldenTicket() >= 0)) {
                        showToast("没有金椒了！");
                    } else if (UserManageBean.userBean.getUserGoldenTicket() > 10) {
                        viewHoldertoupiao.readJinjiaonum.setText("10");
                        showToast("主人，金椒很珍贵，省着点用哦！");
                    } else {
                        viewHoldertoupiao.readJinjiaonum.setText(String.valueOf(UserManageBean.userBean.getUserGoldenTicket()));
                    }
                });

                viewHoldertoupiao.readTouwei.setOnClickListener(v -> {
                    if (!UserManageBean.isLogin(Reading2Activity.this)) {
                        if (popupWindowgive != null && popupWindowgive.isShowing()) {
                            popupWindowgive.dismiss();
                        }

                        return;
                    }
                    if (Integer.valueOf(viewHoldertoupiao.readJinjiaonum.getText().toString()) > UserManageBean.userBean.getUserGoldenTicket()) {
                        showToast("主人，金椒不够了！");
                        return;
                    } else if (Integer.valueOf(viewHoldertoupiao.readJinjiaonum.getText().toString()) < 1) {
                        showToast("主人，请大方一点吧！");
                        return;
                    }
                    toTouweijinpiao();
                });
                popupWindowgive = new PopupWindow(contentView);
                //使其聚集
                popupWindowgive.setFocusable(true);
                // 设置允许在外点击消失
                popupWindowgive.setOutsideTouchable(true);
                //这个是为了点击“返回Back”也能使其消失，并且并不会影响背景
                popupWindowgive.setBackgroundDrawable(new BitmapDrawable(getResources()));
                // 设置SelectPicPopupWindow弹出窗体的宽
                popupWindowgive.setWidth(ScreenUtils.getScreenWidth());
                popupWindowgive.setHeight(ScreenUtils.getScreenHeight() / 4);
                // 设置SelectPicPopupWindow弹出窗体动画效果
                popupWindowgive.setAnimationStyle(R.style.AnimBottom);
                //popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.back_search_img));
                popupWindowgive.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                break;
            case 4:
                contentView = LayoutInflater.from(this).inflate(R.layout.readprogressbar, null);
                viewHolderreadprogressbar = new ViewHolderreadprogressbar(contentView);
                popuWindoeprogressbar = new PopupWindow(contentView);
                popuWindoeprogressbar.setOnDismissListener(() -> movetitle.setVisibility(View.GONE));
                viewHolderreadprogressbar.readseekbar.setProgress((currentChapter + 1) * 100 / mChapterList.size());
                viewHolderreadprogressbar.readseekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        if (!isDianjinext) {
                            if (progress * mChapterList.size() / 100 < 1) {
                                readtexttitle.setText(mChapterList.get(progress * mChapterList.size() / 100).getChapterTitle());
                                currentChapter = 0;
                            } else {
                                readtexttitle.setText(mChapterList.get(progress * mChapterList.size() / 100 - 1).getChapterTitle());
                                currentChapter = progress * mChapterList.size() / 100 - 1;
                            }
                            movetitle.setTranslationX(ScreenUtils.getNum(Reading2Activity.this, progress * 3));
                            baifenbi.setText(String.valueOf((float) ((currentChapter + 1) * 100 / mChapterList.size())) + "%");
                        }

                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        if (!isDianjinext) {
                            mPageWidget.setPosition(new int[]{currentChapter, 0, 0, 1, 0});
                        }


                    }
                });
                viewHolderreadprogressbar.lastchapter.setOnClickListener(v -> {
                    isDianjinext = true;
                    if (currentChapter > 0) {
                        viewHolderreadprogressbar.readseekbar.setProgress(StringTool.getIntnum((double) (currentChapter) * 100 / mChapterList.size()));
                        readtexttitle.setText(mChapterList.get(currentChapter - 1).getChapterTitle());
                        movetitle.setTranslationX(ScreenUtils.getNum(Reading2Activity.this, StringTool.getIntnum((double) currentChapter * 100 / mChapterList.size()) * 3));
                        baifenbi.setText(String.valueOf((float) (currentChapter * 100 / mChapterList.size())) + "%");
                        currentChapter--;
                        mPageWidget.setPosition(new int[]{currentChapter, 0, 0, 1, 0});

                    } else {
                        showToast("没有上一章了");
                    }
                    isDianjinext = false;
                });
                viewHolderreadprogressbar.nextchapter.setOnClickListener(v -> {
                    isDianjinext = true;
                    if (currentChapter < mChapterList.size() - 1) {
                        viewHolderreadprogressbar.readseekbar.setProgress(StringTool.getIntnum((double) (currentChapter + 2) * 100 / mChapterList.size()));
                        readtexttitle.setText(mChapterList.get(currentChapter + 1).getChapterTitle());
                        movetitle.setTranslationX(ScreenUtils.getNum(Reading2Activity.this, StringTool.getIntnum((double) (currentChapter + 2) * 100 / mChapterList.size()) * 3));
                        baifenbi.setText(String.valueOf((float) ((currentChapter + 2) * 100 / mChapterList.size())) + "%");
                        currentChapter++;
                        mPageWidget.setPosition(new int[]{currentChapter, 0, 0, 1, 0});

                    } else {
                        showToast("没有下一章了");
                    }
                    isDianjinext = false;
                });
                //使其聚集
                popuWindoeprogressbar.setFocusable(true);
                // 设置允许在外点击消失
                popuWindoeprogressbar.setOutsideTouchable(true);
                //这个是为了点击“返回Back”也能使其消失，并且并不会影响背景
                popuWindoeprogressbar.setBackgroundDrawable(new BitmapDrawable(getResources()));
                // 设置SelectPicPopupWindow弹出窗体的宽
                popuWindoeprogressbar.setWidth(ScreenUtils.getScreenWidth());
                popuWindoeprogressbar.setHeight(ScreenUtils.getScreenHeight() / 7);
                // 设置SelectPicPopupWindow弹出窗体动画效果
                popuWindoeprogressbar.setAnimationStyle(R.style.AnimBottom);
                //popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.back_search_img));
                popuWindoeprogressbar.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                break;
        }

    }

    private boolean isDianjinext = false;

    private Receiver receiver;

    class Receiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (mPageWidget != null) {
                if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
                    int level = intent.getIntExtra("level", 0);
                    mPageWidget.setBattery(100 - level);
                }
            }
        }
    }

    //设置里的点击事件
    @SuppressLint("SetTextI18n")
    private void viewHolderClick(View v) {
        v.setOnClickListener(v1 -> {
            switch (v1.getId()) {
                case R.id.addzitiread:
                    if (Integer.valueOf(viewHolder.zitinumread.getText().toString()) >= 25) {
                        showToast("已经是最大字体了");
                    } else {
                        viewHolder.zitinumread.setText(String.valueOf(Integer.valueOf(viewHolder.zitinumread.getText().toString()) + 1));
                        mPageWidget.setFontSize(ScreenUtils.getNum(Reading2Activity.this, Integer.valueOf(viewHolder.zitinumread.getText().toString())));
                    }
                    break;
                case R.id.zitisubtractread:
                    if (Integer.valueOf(viewHolder.zitinumread.getText().toString()) <= 14) {
                        showToast("已经是最小字体了");
                    } else {
                        viewHolder.zitinumread.setText(String.valueOf(Integer.valueOf(viewHolder.zitinumread.getText().toString()) - 1));
                        mPageWidget.setFontSize(ScreenUtils.getNum(Reading2Activity.this, Integer.valueOf(viewHolder.zitinumread.getText().toString())));
                    }
                    break;
                case R.id.zitisystem:
                    viewHolder.zitinumread.setText("16");
                    mPageWidget.setFontSize(ScreenUtils.getNum(Reading2Activity.this, Integer.valueOf(viewHolder.zitinumread.getText().toString())));
                    break;
                /* case R.id.simulationread:
                 *//*flipwey = 1;
                    toflipwayselect();
                    pos = mPageWidget.getReadPos();
                    SettingManager.getInstance().saveFontSize(bookId, mPageWidget.getFontSize());
                    SettingManager.getInstance().saveReadProgress(bookId, pos[0], pos[1], pos[2], pos[3], pos[4]);
                    mPageWidget = new PageWidget(Reading2Activity.this, bookId, mChapterList, readlistener, readBaocunBean);
                    mPageWidget.init();
                    readWidget.removeAllViews();
                    readWidget.addView(mPageWidget);*//*
                    break;
                case R.id.coverageread:
                    showToast("小伙伴们正在努力添加此功能，请耐心等待。");
                    *//*flipwey = 2;
                    toflipwayselect();
                    pos = mPageWidget.getReadPos();
                    SettingManager.getInstance().saveFontSize(bookId, mPageWidget.getFontSize());
                    SettingManager.getInstance().saveReadProgress(bookId, pos[0], pos[1], pos[2], pos[3], pos[4]);
                    mPageWidget = new OverlappedWidget(Reading2Activity.this, bookId, mChapterList, readlistener, readBaocunBean);
                    mPageWidget.init();
                    readWidget.removeAllViews();
                    readWidget.addView(mPageWidget);*//*
                    break;
                case R.id.nopagingread:
                    showToast("小伙伴们正在努力添加此功能，请耐心等待。");
                   *//* flipwey = 3;
                    toflipwayselect();
                    pos = mPageWidget.getReadPos();
                    SettingManager.getInstance().saveFontSize(bookId, mPageWidget.getFontSize());
                    SettingManager.getInstance().saveReadProgress(bookId, pos[0], pos[1], pos[2], pos[3], pos[4]);
                    mPageWidget = new NoAimWidget(Reading2Activity.this, bookId, mChapterList, readlistener, readBaocunBean);
                    mPageWidget.init();
                    readWidget.removeAllViews();
                    readWidget.addView(mPageWidget);*//*
                    break;*/
                case R.id.selfreadset:
                    if (!UserManageBean.isLogin(Reading2Activity.this)) {
                        viewHolder.selfreadset.setOpened(false);
                        return;
                    }
                    isZidong = viewHolder.selfreadset.isOpened();
                    if (isZidong) {
                        toZidong("1");
                    } else {
                        toZidong("0");
                    }
                    break;
                case R.id.runseekbarxitong:
                    seekposition = ScreenUtils.getScreenBrightness();
                    viewHolder.sunseekbarread.setProgress(seekposition);
                    ScreenUtils.setScreenBrightness(seekposition, Reading2Activity.this);
                    break;
            }
        });
    }


    class ViewHolderreadprogressbar {
        @BindView(R.id.lastchapter)
        TextView lastchapter;
        @BindView(R.id.nextchapter)
        TextView nextchapter;
        @BindView(R.id.readseekbar)
        SeekBar readseekbar;

        ViewHolderreadprogressbar(View view) {
            ButterKnife.bind(this, view);
        }
    }


    //投喂小米椒
    private void toTouweixmj() {
        if (mChapterList.size() < 1) {
            showToast("亲，出错了，请重新进哦！");
            return;
        }
        OkHttpUtils.post(HttpManager.IP + "/user-RecommendationTicket")
                .headers("timestr",  String.valueOf(System.currentTimeMillis()/180000) )
                .headers("sign",Md5.encryption(SettingManager.getInstance().getUUID()+"#"+android.os.Build.BRAND+"#"+android.os.Build.MODEL+"#"+Md5.encryption(SettingManager.getInstance().getUUID().substring(7,25))+"#"+String.valueOf(System.currentTimeMillis()/180000)))
                .params("recommendTicketCount", "1")
                .params("authorId", String.valueOf(mChapterList.get(0).getBookWriterId()))
                .params("bookid", bookId)
                .params("bookName", bookName)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject json = new JSONObject(s);
                            if (200 == json.getInt("returnCode")) {
                                showToast(json.getString("msg"));
                                //toChangeBookData(1);
                                UserManageBean.userBean.setUserRecommendTicket(UserManageBean.userBean.getUserRecommendTicket() - 1);
                                UserManageBean.backgroundRiches(Reading2Activity.this);
                                togiveimage();
                                hideorshowbottom();
                            } else if (400 == json.getInt("returnCode")) {
                                Intent intent = new Intent(Reading2Activity.this, LoginActivity.class);
                                startActivity(intent);
                            }
                            showToast(json.getString("msg"));

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    //设置右下方图片
    private void togiveimage() {
        if (UserManageBean.isLogin() && UserManageBean.userBean.getUserRecommendTicket() < 1) {
            giveReadxmj.setImageResource(R.mipmap.give_readlj);
            giveread.setVisibility(View.GONE);
        } else {
            giveReadxmj.setImageResource(R.mipmap.give_readxmj);
            giveread.setVisibility(View.VISIBLE);
        }
    }

    //设置右下方图片的显示和隐藏动画
    private void toShowImage(boolean isShow) {
        AnimationSet aset = new AnimationSet(true);
        AlphaAnimation aa;
        if (!isShow) {
            aa = new AlphaAnimation(1, 0);
        } else {
            aa = new AlphaAnimation(0, 1);
        }
        aa.setDuration(500);
        aset.addAnimation(aa);
        giveReadxmj.startAnimation(aset);
    }

    //投喂金椒
    private void toTouweijinpiao() {
        if (mChapterList.size() < 1) {
            showToast("亲，出错了，请重新进哦！");
            return;
        }
        OkHttpUtils.post(HttpManager.IP + "/user-RewardGonderTicket")

                .params("goldenTicketCount", viewHoldertoupiao.readJinjiaonum.getText().toString())
                .params("bookid", bookId)
                .params("authorId", String.valueOf(mChapterList.get(0).getBookWriterId()))
                .params("bookName", bookName)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject json = new JSONObject(s);
                            if (200 == json.getInt("returnCode")) {
                                showToast(json.getString("msg"));
                                UserManageBean.backgroundRiches(Reading2Activity.this);
                            } else {
                                if (400 == json.getInt("returnCode")) {
                                    Intent intent = new Intent(Reading2Activity.this, LoginActivity.class);
                                    startActivity(intent);
                                }
                                showToast(json.getString("msg"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (UserManageBean.isLogin()) {
            isZidong();
            isShujia();
            togiveimage();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //从段评返回加载短评数量
        if (requestCode == CodeManager.Segment_review_read && resultCode == CodeManager.Segment_review_read) {
            readlistener.onLoadChapterFailure(currentChapter);
        } else if (requestCode == CodeManager.Binding_read && resultCode == CodeManager.Binding_read) {
            if (phoneBangdingDialog != null) {
                phoneBangdingDialog.setQuhao(data.getStringExtra("countryNumber"));
            }
        } else if (requestCode == CodeManager.purs_read || requestCode == CodeManager.invite_friends) {
            mPageWidget.refreshPage();
        }else if (requestCode==CodeManager.istoOverpage){
            isToOverpage=false;
        }
    }

    class ViewHolder {
        @BindView(R.id.sunseekbarread)
        SeekBar sunseekbarread;
        @BindView(R.id.runseekbarxitong)
        SuperButton runseekbarxitong;
        @BindView(R.id.zitisubtractread)
        ImageView zitisubtractread;
        @BindView(R.id.zitinumread)
        TextView zitinumread;
        @BindView(R.id.addzitiread)
        ImageView addzitiread;
        @BindView(R.id.zitisystem)
        SuperButton zitisystem;
        @BindView(R.id.readsetbeijinglist)
        RecyclerView readsetbeijinglist;
        @BindView(R.id.selfreadset)
        SwitchView selfreadset;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    class ViewHolderGolden {
        @BindView(R.id.jinjiaobalance)
        TextView jinjiaobalance;
        @BindView(R.id.read_subtract)
        SuperButton readSubtract;
        @BindView(R.id.read_jinjiaonum)
        SuperButton readJinjiaonum;
        @BindView(R.id.read_add)
        SuperButton readAdd;
        @BindView(R.id.read_all)
        SuperButton readAll;
        @BindView(R.id.read_touwei)
        SuperButton readTouwei;

        ViewHolderGolden(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
